package com.test.login.controller;

import com.alibaba.fastjson.JSON;
import com.test.login.model.User;
import com.test.login.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;


@Controller
@RequestMapping("/login")
public class LoginController {

    private static final String PATH = "Login/";

    @Resource
    private UserService userService;

    @GetMapping("/index")
    public String index() {
        return PATH + "index";
    }

    @GetMapping("/edit")
    public String edit(String id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return PATH + "edit";
    }

    @PostMapping("/save")
    @ResponseBody
    public String save(User user) {
        if (userService.save(user) > 0) {
            return "0";
        } else {
            return "1";
        }
    }

    @GetMapping("/list")
    @ResponseBody
    public String list() {
        return JSON.toJSONString(userService.list());
    }

}
